package kuwo

import (
	"api-go/cache"
	"api-go/serializer"
	"api-go/util"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
)

type Banner struct {
}

var ctx = context.Background()

//获取首页轮播图
func (service *Banner) Banner() *serializer.Response {
	//定义redis key和判断redis是否有该值
	redisKey := "kuwo-banner"
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		url := "http://www.kuwo.cn/api/www/banner/index/bannerList?&httpsStatus=1"

		res, err := util.KuwoGet(url)
		if err != nil {
			return err
		}
		//将结果转为Json数据
		b, e := json.Marshal(res)
		if e != nil {
			fmt.Println(err)
		}
		//转为string存入redis
		e = cache.RedisClient.Set(ctx, redisKey, string(b), 24*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}

		return serializer.OkResponse(res)
	} else if err != nil {
		fmt.Println("err2", err)
		return serializer.ErrorResponse(serializer.RedisError)
	} else {
		//将从redis获取的结果（string类型）转为map[string]inerface{}
		bodyMapData := map[string]interface{}{}
		err = json.Unmarshal([]byte(redisResult), &bodyMapData)
		if err != nil {
			fmt.Println("err3", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}
		return serializer.OkResponse(bodyMapData)
	}

}
